import json
import re
import os
import urllib.request
from urllib.parse import urlparse, urlunparse
import datetime

# 读取JSON文件
with open('classPhotoByUserId.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 创建以当前日期命名的文件夹
current_date = datetime.datetime.now().strftime('%Y%m%d')
os.makedirs(current_date, exist_ok=True)

# 存储所有图片URL
image_urls = []

# 提取所有图片URL
for item in data['data']['list']:
    content = item['content']
    # 使用正则表达式匹配src属性
    urls = re.findall(r'src="([^"]+)"', content)
    for url in urls:
        # 移除查询参数
        parsed_url = urlparse(url)
        clean_url = urlunparse((parsed_url.scheme, parsed_url.netloc, parsed_url.path, '', '', ''))
        image_urls.append(clean_url)

# 去重
image_urls = list(set(image_urls))

print(f"找到 {len(image_urls)} 个唯一的图片URL")

# 下载所有图片
for i, url in enumerate(image_urls):
    try:
        # 获取文件名
        parsed_url = urlparse(url)
        filename = os.path.basename(parsed_url.path)
        
        # 构造保存路径
        save_path = os.path.join(current_date, filename)
        
        # 下载图片
        urllib.request.urlretrieve(url, save_path)
        print(f"已下载 {i+1}/{len(image_urls)}: {filename}")
    except Exception as e:
        print(f"下载失败 {url}: {e}")

print(f"所有图片已保存到 {current_date} 文件夹中")